package test.fanxin.method;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GenericMethodProcess {
	/**
	 * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com Date: 2012-1-3
	 * Description: 1. this method will convert bean to string in this format:
	 * field_name_1
	 * =field_value_1;field_name_12=field_value_2;field_name_3=field_value_3...
	 * 2. The field of the bean can only be basic java data type like 'int' or
	 * object type like 'String'; If you want support self-define class type
	 * like "com.ross.generic.CarBean", you need extend the method -:)
	 * 
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public <T> String toString(T oT) throws Exception  {
		// define return value
		String sRet = "";
		// temporary variables
		String sGetMethodName = "";
		String sFieldName = "";
		Method oMethod;
		Field[] oFields = oT.getClass().getDeclaredFields();
		if (null != oFields) {
			for (int i = 0; i < oFields.length; i++) {
				// to access the private field
				oFields[i].setAccessible(true);
				// get field name
				sFieldName = oFields[i].getName();
				// get method name
				if (sFieldName.length() > 1) {
					sGetMethodName = "get"
							+ sFieldName.substring(0, 1).toUpperCase()
							+ sFieldName.substring(1, sFieldName.length());
				} else {
					sGetMethodName = "get" + sFieldName.toUpperCase();
				}
				// get set method
				oMethod = oT.getClass().getMethod(sGetMethodName);
				// get value
				sRet = sRet + sFieldName + "=***" + oMethod.invoke(oT) + "+++;";
			}
		}
		// remove the last separator: ';'
		if (!"".equals(sRet)) {
			sRet = sRet.substring(0, sRet.length() - 1);
		}
		return sRet;
	}
}
